import logging
from urllib import parse

import pytest
from bs4 import BeautifulSoup
from config import datas
from common.request_util_test import RequestUtil
from common.test_yaml_util_test import YamlUtil


class TestLogin:
    @pytest.mark.parametrize('logininfo', YamlUtil().read_testcase_yaml('v24.06/login/1_login.yaml'))
    def test_get_login(self, logininfo, get_env_info):
        # 1.触发管理面的登录功能
        baseUrl = get_env_info
        url = baseUrl + logininfo['request']['url']
        method = logininfo['request']['method']
        req = RequestUtil().send_request(method, url)
        Location1 = req.headers['Location']
        # 2.生成用户授权码接口
        url2=  Location1
        req2 = RequestUtil().send_request('get',url2)
        Location2 = req2.headers['Location']
        # 3.获取用户登录界面接口
        url3=baseUrl+Location2
        req3 = RequestUtil().send_request('get',url3)
        soup = BeautifulSoup(req3.text, 'html.parser')
        all_input_label = soup.find_all('input')
        for i in all_input_label:
            if i['name'] ==  'gorilla.csrf.Token':
                gorilla_csrf_Token = i['value']
                print('打印gorilla_csrf_Token：',gorilla_csrf_Token)
            if i['name'] == 'then':
                get_then=i['value']
                print('打印then:',get_then)
        # 4.发送用户账号密码接口
        url4 = baseUrl + '/oauth2/auth/login/fuyaoPasswordProvider'
        header = {"Content-Type": "application/x-www-form-urlencoded"}
        data = { "username": datas.username, "password":datas.password, "gorilla.csrf.Token": gorilla_csrf_Token, "then":get_then}
        data=parse.urlencode(data)
        req4 = RequestUtil().send_request('post', url4, headers=header,data=data)
        Location3 = req4.headers['Location']
        # 5.生成用户授权码接口
        url5= baseUrl+Location3
        req5=RequestUtil().send_request('get',url5)
        Location4 = req5.headers['Location']
        # 6.授权code回调接口
        url6 = Location4
        req6 = RequestUtil().send_request('get', url6)
        # 7.检查登录成功
        url7 = baseUrl +'/'
        req7 = RequestUtil().send_request('get', url7)
        assert req7.status_code == 200





if __name__ == '__main__':
    pytest.main(["-s", "test_1login.py"])


